package com.yuandian.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.business_monitor.entity.E2eStudyTask;
import com.yuandian.api.business_monitor.po.E2eStudyCollect;
import com.yuandian.api.management.vo.EndToEndRelationshipVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.management.mapper.E2eStudyTaskMapper;
import com.yuandian.management.service.ConfEndToEndRelationshipService;
import com.yuandian.management.service.IE2eStudyTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 说明：端到端学习任务service实现
 *
 * @Author zfsn
 * @Date 2023/7/12 14:18
 */
@Service
public class E2eStudyTaskServiceImpl extends ServiceImpl<E2eStudyTaskMapper, E2eStudyTask>
		implements IE2eStudyTaskService {

	@Autowired
	private E2eStudyTaskMapper e2eStudyTaskMapper;
	@Autowired
	private ConfEndToEndRelationshipService endToEndRelationshipService;


	/**
	 * 同步配置给步骤端到端学习
	 *
	 * @param list 端到端学习汇总对象集合
	 * @return 通用返回结果
	 */
	@Override
	public R sync(List<E2eStudyCollect> list) {
		int syncCount = 0;
		int existCount = 0;
		for (E2eStudyCollect e2eStudyCollect : list) {
			int count = e2eStudyTaskMapper.queryE2eConfigExist(e2eStudyCollect);
			if (count > 0) {
				existCount++;
				continue;
			}
			//父节点
			String parentNodeId = String.valueOf(IdUtil.getSnowflakeNextId());
			EndToEndRelationshipVo parentNode = new EndToEndRelationshipVo();
			parentNode.setBusinessCode(e2eStudyCollect.getBusinessCode());
			parentNode.setSystemId(Integer.valueOf(e2eStudyCollect.getSystemId()));
			parentNode.setStepCode(e2eStudyCollect.getStepCode());
			parentNode.setSegmentId(e2eStudyCollect.getBeforeSegmentId());
			parentNode.setResourceCode(e2eStudyCollect.getBeforeResourceCode());
			parentNode.setNodeId(parentNodeId);
			endToEndRelationshipService.addNode(parentNode);
			//子节点
			EndToEndRelationshipVo childNode = new EndToEndRelationshipVo();
			BeanUtil.copyProperties(parentNode, childNode);
			childNode.setSegmentId(e2eStudyCollect.getAfterSegmentId());
			childNode.setResourceCode(e2eStudyCollect.getAfterResourceCode());
			childNode.setParentResourceCode(e2eStudyCollect.getBeforeResourceCode());
			endToEndRelationshipService.addNode(childNode);

//			e2eStudyTaskMapper.sync(e2eStudyCollect);

			syncCount++;
		}
		return R.ok("共 " + list.size() + " 条配置需要同步，" + syncCount
				+ " 条同步完成，" + existCount + " 条配置已经存在无需同步");
	}
}
